import cv2
import os
# 读取图像
filename = os.path.dirname(__file__) + '/vtest.avi'
cap = cv2.VideoCapture(filename)
# 创建背景提取器
bgs = cv2.createBackgroundSubtractorMOG2()
count = 0

while True:
    # 提取每一帧
    ret,frame = cap.read()
    if not ret:
        break
    count += 1 
    # 得到前景
    fgmask = bgs.apply(frame)
    _,fgmask = cv2.threshold(fgmask,130,0xff,cv2.THRESH_BINARY)
    # 得到背景
    bg = bgs.getBackgroundImage()
    # 将前景在原图中框出来
    _,cnts,_ = cv2.findContours(fgmask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    for c in cnts:
        # 面积过小的不画
        area = cv2.contourArea(c)
        if area < 50:
            continue
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(frame,(x,y),(x+w,y+h),color=[0,0,255])
        cv2.putText(frame,str(area),(x,y),cv2.FONT_HERSHEY_PLAIN,1,color=[0,0,255])

    # 播放原视频，前景，背景
    cv2.putText(frame,str(count),(2,60),cv2.FONT_HERSHEY_PLAIN,2,color=[0,0,0xff])
    cv2.putText(fgmask,str(count),(2,60),cv2.FONT_HERSHEY_PLAIN,2,color=[0,0,0xff])
    cv2.putText(bg,str(count),(2,60),cv2.FONT_HERSHEY_PLAIN,2,color=[0,0,0xff])
    cv2.imshow('origin',frame)
    cv2.imshow('fount',fgmask)
    cv2.imshow('background',bg)

    # 退出播放和暂停播放控制
    c = cv2.waitKey(66)
    if c == -1:
        continue
    elif chr(c) == 'q':
        break
    elif chr(c) == ' ':
        cv2.waitKey()


cv2.destroyAllWindows()